/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.ArrayList;
import java.util.List;
import models.Student;
import models.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Achie
 */
public class UserDao {

    private final Session session;

    public UserDao(Session session) {
        this.session = session;
    }

    public List<User> findAll() {
        Transaction tx = session.beginTransaction();
        List<User> list = session.createQuery("from User").list();
        tx.commit();
        return list;
    }

    public boolean save(User user) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(user);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //get the list of users who are not activated yet
    public List<User> findAllUnactivatedUsers() {
        Transaction tx = session.beginTransaction();
        String sql = "SELECT m.id FROM member m, activation a WHERE m.id=a.student_id AND a.activation=false;";
        Query query = session.createSQLQuery(sql);
        List idlist = query.list();
        ArrayList<User> list = new ArrayList<User>();
        for (int i = 0; i < idlist.size(); i++) {
            query = session.createQuery("from User where id= :id").setParameter("id", Long.parseLong(idlist.get(i).toString()));
            User user = get(Long.parseLong(idlist.get(i).toString()));
            list.add(user);
        }
        tx.commit();
        return list;
    }

    public boolean update(User user) {
        try {
            Transaction tx = session.beginTransaction();
            session.update(user);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public User get(long member_id) {
        return (User) session.get(User.class, member_id);
    }

    public void delete(User user) {
        Transaction tx = session.beginTransaction();
        session.delete(user);
        tx.commit();
    }

    //find all user objects with email (string)
    public List<User> findAllByEmail(String email) {
        Transaction tx = session.beginTransaction();
        List<User> list = session.createQuery("from User where email= :email").setParameter("email", email).list();
        tx.commit();
        return list;
    }
}
